#include "mmTest_BadPoint.h"

#include "xxFileProcess.h"
#include "mmFile_Paras.h"

_mmTest_BadPoint mmTest_BadPoint;

bool _mmTest_BadPoint::_Init() {
	if (iiProject.Flag_InitSystem == false) {
		return false;
	}
	Limit_Low = xx::InitIni(iniField, L"Limit_Low", double(0), mmFile_Paras.iniModelPath());
	Limit_High = xx::InitIni(iniField, L"Limit_High", double(10), mmFile_Paras.iniModelPath());

	Flag_Inited = TRUE;
	return TRUE;
}

bool _mmTest_BadPoint::RunTest(uuByteFig& ByteFig) {
	Mat FigMat = xx::ByteFigToMat(ByteFig);
	if (FigMat.rows == 0 || FigMat.cols == 0 || FigMat.channels() == 0) {
		return false;
	}

	cvtColor(FigMat, FigMat, CV_BGR2GRAY);

	DarkNum = 0; WhiteNum = 0;
	for (int i = 0; i < iiTEST_BADPOINT_MaxNum; i++) {
		DarkPoints[i].x = 0;
		DarkPoints[i].y = 0;
		WhitePoints[i].x = 0;
		WhitePoints[i].y = 0;
	}

	for (int i = 2; i < FigMat.rows - StepY; i += StepY) {
		for (int j = 2; j < FigMat.cols - StepX; j += StepX) {
			Mat FigSub = FigMat.rowRange(i, i + StepY - 1).colRange(j, j + StepX - 1);
			Scalar SubSum = sum(FigSub);
			float aveSubSum = float(SubSum[0]) / float(StepX * StepY);
			for (int m = 0; m < StepY; m++) {
				for (int n = 0; n < StepX; n++) {
					int CurPixel = FigMat.at<uchar>(i + m, j + n);
					if (CurPixel > aveSubSum*Limit_High) {
						WhitePoints[WhiteNum].x = j + n;
						WhitePoints[WhiteNum].y = i + m;
						WhiteNum++;
						if (WhiteNum >= iiTEST_BADPOINT_MaxNum) {
							return TRUE;
						}
					}
					if (CurPixel < aveSubSum*DarkNum) {
						DarkPoints[DarkNum].x = j + n;
						DarkPoints[DarkNum].y = i + m;
						DarkNum++;
						if (DarkNum >= iiTEST_BADPOINT_MaxNum) {
							return TRUE;
						}
					}
				}
			}
		}
	}


	SumNum = DarkNum + WhiteNum;

	Flag_TestResult = (SumNum == 0) ? TRUE : false;

	return TRUE;
}
